package com.qf.hospital.controller;

import com.alibaba.druid.util.StringUtils;
import com.qf.hospital.enums.HospitalExceptionEnums;
import com.qf.hospital.vo.R;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zjw
 * @description 用户认证等操作的Controller
 * @date 2021/10/15 14:27
 */
@RestController
public class LoginController {

    private Logger log = LoggerFactory.getLogger(LoginController.class);


    /**
     * 登录功能
     * @param loginname  用户名
     * @param pwd  密码
     * @return
     */
    @PostMapping("/sel/doLogin")
    public R doLogin(String loginname, String pwd){
        //1. 校验请求参数
        if(StringUtils.isEmpty(loginname) || StringUtils.isEmpty(pwd)){
            log.info("【登录功能】 请求参数异常，用户名和密码均为必填项！");
            return R.error(HospitalExceptionEnums.REQUEST_PARAMETER_ERROR,"用户名和密码均为必填项！");
        }

        //2. 获取Subject主体
        Subject subject = SecurityUtils.getSubject();

        //3. 执行认证
        subject.login(new UsernamePasswordToken(loginname,pwd));

        //4. 登录成功
        return R.ok("登录成功！");
    }


    /**
     * 退出登录
     * @return
     */
    @GetMapping("/sel/logout")
    public R logout(){
        //1. 获取主体
        Subject subject = SecurityUtils.getSubject();

        //2. 退出登录
        subject.logout();

        //3. 返回成功
        return R.ok("退出登录成功！");
    }



}
